package com.example.hms.service.servicelmpl;

import com.example.hms.dao.BlackListDao;
import com.example.hms.entity.BlackList;
import com.example.hms.entity.SystemLog;
import com.example.hms.service.BlackListService;
import com.example.hms.service.SystemLogService;
import com.example.hms.util.Result;
import com.example.hms.util.ResultSubmit;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public class BlackListServiceImpl implements BlackListService {
    @Resource
    private BlackListDao blackListDao;

    @Resource
    SystemLogService systemLogService;

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public Result selectAllBlackList(String  blackListId,String customerId,String state) {
        List<BlackList> blackLists = blackListDao.selectAllBlackList(blackListId,  customerId, state);
        return ResultSubmit.success(blackLists);
    }

    //    拉入黑名单
    @Override
    public Result insert(BlackList blackList, HttpServletRequest request) {
        // 获取债务信息
        String customerId = String.valueOf(blackList.getCustomerId());
        String cancelTime = format.format(new Date());

        Map<String, Object> debtInfo = blackListDao.selectBlackListDebt(customerId, cancelTime);

        BigDecimal debtMoney = (BigDecimal) debtInfo.get("debtMoney");
        Long debtDay = (Long) debtInfo.get("debtDay");

        // 设置债务信息
        blackList.setDebtMoney(BigDecimal.valueOf(debtMoney != null ? debtMoney.doubleValue() : 0));
        blackList.setDebtDay(String.valueOf(debtDay != null ? debtDay : 0));
        if (debtMoney == null) {
            // 事务回滚(手动回滚)
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("该用户还未退房，不能加入黑名单");
        }
        // 判断是否满足信誉扣分条件（每欠款100元扣1分），原始信誉分为100分，最低0分
        if (debtMoney != null && debtMoney.compareTo(BigDecimal.ZERO) > 0) {
            // 计算应扣分数：向下取整除法
            int deductionPoints = debtMoney.divideToIntegralValue(new BigDecimal("100")).intValueExact();

            // 获取当前信誉分，若为空则设为100分
            String reputationStr = blackList.getReputation();
            Integer currentReputation = 100; // 默认为100分
            try {
                if (reputationStr != null && !reputationStr.trim().isEmpty()) {
                    reputationStr = currentReputation.toString();
                }
            } catch (NumberFormatException ignored) {
                // 忽略非法格式，默认使用100分
            }

            // 扣分计算
            int newReputation = currentReputation - deductionPoints;

            // 最低为0分
            if (newReputation < 0) {
                newReputation = 0;
            }

            blackList.setReputation(String.valueOf(newReputation));
            // 新增：根据信誉分设置信誉等级
            String reputationLevel = "信用程度正常"; // 默认值
            if (newReputation >= 0 && newReputation < 35) {
                reputationLevel = "重度失信";
            } else if (newReputation < 60) {
                reputationLevel = "中度失信";
            } else if (newReputation < 95) {
                reputationLevel = "轻度失信";
            }
            blackList.setState(reputationLevel);
        }

        blackList.setDataUpdateTime(format.format(new Date()));
        blackList.setBlackListId(Math.abs((int) System.currentTimeMillis()));
        blackList.setDeleteIdentity("未删除");

        int insert1 = blackListDao.insert(blackList);

        //todo  系统记录
        SystemLog systemLog = new SystemLog();
        systemLog.setUserId((Integer) request.getSession().getAttribute("userId"));
        systemLog.setRoleName((String) request.getSession().getAttribute("roleName"));
        systemLog.setCreateTime(format.format(new Date()));
        systemLog.setUseTableName("blackList");
        systemLog.setUseTableDataIdAfter(String.valueOf(
                blackListDao.selectAllBlackList(String.valueOf(blackList.getBlackListId()),String.valueOf(blackList.getCustomerId()),blackList.getState()).
                        get(0).getBlackListTableId()));
        systemLog.setUseType("拉入黑名单");
        systemLogService.insert(systemLog);


        if (insert1 != 0) {
            return ResultSubmit.success("添加成功");
        }
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return ResultSubmit.error("添加失败");
    }

    //    修改严重程度与信誉积分（欠款金额与欠款天数与订单表相接）
    @Override
    public Result update(BlackList blackList, HttpServletRequest request) {
        int update1 = blackListDao.update(blackList);
        blackList.setDataUpdateTime(format.format(new Date()));
        blackList.setDeleteIdentity("未删除");

        int insert1 = blackListDao.insert(blackList);

        // todo 系统记录
        SystemLog systemLog = new SystemLog();
        systemLog.setUserId((Integer) request.getSession().getAttribute("userId"));
        systemLog.setRoleName((String) request.getSession().getAttribute("roleName"));
        systemLog.setCreateTime(format.format(new Date()));
        systemLog.setUseTableName("blackList");
        systemLog.setUseTableDataIdAfter(String.valueOf(
                blackListDao.selectAllBlackList(String.valueOf(blackList.getBlackListId()),String.valueOf(blackList.getCustomerId()),blackList.getState()).
                        get(0).getBlackListTableId()));
        systemLog.setUseTableDataIdBefore(String.valueOf(
                blackListDao.selectAllBlackList(String.valueOf(blackList.getBlackListId()),String.valueOf(blackList.getCustomerId()),blackList.getState()).
                        get(0).getBlackListTableId()));
        systemLog.setUseType("修改黑名单");
        systemLogService.insert(systemLog);

        if (update1 == 1 || insert1 == 1) {
            return ResultSubmit.success("修改成功");
        } else {
            // 事务回滚(手动回滚)
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //不成功则返回报错并回滚
            return ResultSubmit.error("修改失败");
        }
    }

    //    拉出黑名单
    @Override
    public Result delete(BlackList blackList,  HttpServletRequest request) {
        Integer tableId = blackListDao.selectAllBlackList(String.valueOf(blackList.getBlackListId()),null,null).get(0).getBlackListTableId();
        int delete1 = blackListDao.update(blackList);
        // todo 系统记录
        SystemLog systemLog = new SystemLog();
        systemLog.setUserId((Integer) request.getSession().getAttribute("userId"));
        systemLog.setRoleName((String) request.getSession().getAttribute("roleName"));
        systemLog.setCreateTime(format.format(new Date()));
        systemLog.setUseTableName("blackList");
        systemLog.setUseTableDataIdBefore(String.valueOf(tableId));
        systemLog.setUseType("删除黑名单");
        systemLogService.insert(systemLog);

        if (delete1 != 0) {
            return ResultSubmit.success("删除成功");
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("删除失败");
        }
    }
    @Override
    public Result selectBlackListDebt(String customerId, String cancelTime) {
        Map<String, Object> blackListDebts = blackListDao.selectBlackListDebt(customerId,cancelTime);
        return ResultSubmit.success(blackListDebts);
    }
}
